/**
 * Created by linin-app.com on 2023/6/7 22:22.
 */
const { spawn } = require('child_process');
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8528 });
let  client
let ffmpeg
wss.on('connection',  (ws)=> {
  console.log('Client connected');
  client = ws;

  let _ffmpeg = spawn('ffmpeg', //ffmpeg 自己从官网上载，改成自己路径，或配置成全局变量
    [
    '-i', 'html/1.mp4',
    '-c:v', 'libx264', // 如果原视频已经是264格式可以不转
    '-movflags', 'frag_keyframe+empty_moov+default_base_moof', // 转成fragment mp4
    '-f', 'mp4',
    'pipe:1' // 输出流
  ]);
  ffmpeg = _ffmpeg;
  ffmpeg.stdout.on('data', chunk=>{
    console.log("data")
    ws.send(chunk, {binary: true, mask: false});
    ffmpeg.stdout.pause()
  })

  ws.on('close', event=>{
    console.log('websocket close')
    _ffmpeg.kill();
  })
});

const control = new WebSocket.Server({ port: 8800 });
control.on('connection',  (ws)=> {
  ws.on('message', data=>{
    console.log("control:", data)
    if (data === 'get') {
      ffmpeg && ffmpeg.stdout.resume()
    }
  })
});

const express = require('express');
const app = express();

// Serve static files from the "public" directory
app.use(express.static('html'));

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

